<template>
  <div class="department_box">
    <div class="add_btn_top">
      <div class="sw_btn_box" style="display: flex; align-items: center">
        <div
          :style="{
            color: switchText == '显示筛选' ? '#666666' : '#409EFF',
            fontSize: '14px',
            marginRight: '6px'
          }"
        >
          {{ switchText }}
        </div>
        <el-switch
          v-permission="[4, 'switch']"
          style="margin-right: 10px"
          active-color="#2680D2"
          v-model="isShowScreen"
        >
        </el-switch>
        <el-button
          type="primary"
          size="small"
          @click="handleOpen(tableData, openText == '全部展开' ? false : true)"
          :icon="
            openText == '全部展开' ? 'el-icon-arrow-down' : 'el-icon-arrow-up'
          "
          >{{ openText }}</el-button
        >
        <el-button
          type="primary"
          size="small"
          @click="handleAdd()"
          icon="el-icon-plus"
          v-permission="[1, 'button']"
          >添加</el-button
        >
        <el-button
          v-if="deptIds"
          v-permission="[2, 'button']"
          type="danger"
          size="small"
          @click="handleDel(deptIds)"
          icon="el-icon-delete"
          >删除</el-button
        >
      </div>
    </div>
    <div
      v-permission="[4, 'list']"
      class="department_table"
      :style="{
        width: isShowScreen ? '79%' : '100%'
      }"
    >
      <el-table
        ref="diffeDataTable"
        height="100px"
        v-adaptive
        :data="tableData.slice((pageNum - 1) * pageSize, pageNum * pageSize)"
        style="width: 100%; margin-bottom: 20px"
        row-key="id"
        @select-all="selectAll"
        @selection-change="handleSelectionChange"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <!-- :reserve-selection="true" 数据更新之后保留第一次触发的数据 解决多选不触发问题 -->
        <el-table-column :reserve-selection="true" type="selection" width="55">
        </el-table-column>
        <el-table-column
          prop="name"
          label="名称"
          width="300"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column prop="id" label="id" width="100" align="center">
        </el-table-column>

        <el-table-column
          prop="userCount"
          label="用户数"
          width="100"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="subDeptCount"
          label="子部门数"
          width="100"
          align="center"
        >
        </el-table-column>
        <el-table-column
          align="center"
          prop="remark"
          label="备注"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              icon="el-icon-edit"
              type="primary"
              size="small"
              @click="handleEdit(scope.row)"
              >编辑</el-button
            ><el-button
              v-permission="[2, 'button']"
              type="danger"
              size="small"
              @click="handleDel(scope.row.id)"
              icon="el-icon-delete"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        @pagination="pagination"
        :total="tableData.length"
        :page.sync="pageNum"
        :limit.sync="pageSize"
        :pageSizes.sync="pageSizes"
      />
    </div>

    <div v-if="isShowScreen" class="searchForm">
      <div style="width: 100%" v-init-screen-h>
        <div class="select">筛选</div>
        <div class="">
          <div class="searchText">名称</div>
          <el-input
            class="inputStyle"
            v-model="searchFrom.name"
            clearable
            size="mini"
            placeholder="请输入名称"
          >
          </el-input>
        </div>
      </div>
      <div class="bottomBtn">
        <el-button class="reset" size="mini" style="width: 50%" @click="reSet"
          >重置</el-button
        >
        <el-button
          @click="searchTreeTable"
          class="submit"
          size="mini"
          style="width: 50%"
          type="primary"
          >提交</el-button
        >
      </div>
    </div>
    <el-dialog
      :title="isAdd ? '添加部门' : '编辑部门'"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
      @close="handleClose"
    >
      <el-form
        :model="form"
        ref="formName"
        :rules="rules"
        label-width="70px"
        :inline="false"
        size="small"
      >
        <el-form-item label="名称:" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="顶级部门:" prop="topDep">
          <el-radio-group v-model="form.topDep">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="2">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="部门:" prop="pid" v-if="form.topDep === 2">
          <el-cascader
            clearable
            :popper-class="!seleData.length ? 'user_admin_cascader_nodata' : ''"
            class="w100"
            v-model="form.pid"
            :options="seleData"
            :props="{
              checkStrictly: true, //单选任意一级
              expandTrigger: 'hover',
              value: 'id',
              label: 'name'
            }"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="备注:" prop="remark">
          <el-input
            type="textarea"
            v-model="form.remark"
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button
          v-if="isAdd"
          key="add"
          size="small"
          type="primary"
          @click="onSubmit"
          :loading="sumbitLoading"
          >提交</el-button
        >
        <el-button
          key="edit"
          v-permission="[3, 'switch']"
          v-else
          size="small"
          type="primary"
          @click="onSubmit"
          :loading="sumbitLoading"
          >提交</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/views/common/page";
import { paginationMixins } from "@/mixin/pagination";
import { getDeptList, depDelete, depCreate, depEdit } from "@/api/department";
import "@/assets/style/deviceCss/filterWindow.css";
import _ from "lodash";
export default {
  mixins: [paginationMixins],
  components: {
    Pagination
  },
  data() {
    return {
      tableDataClone: [],
      sumbitLoading: false,
      searchFrom: { name: "" },
      switchText: "显示筛选",
      isShowScreen: false,
      dialogVisible: false,
      tableData: [],
      form: {
        name: "",
        topDep: 1,
        pid: [],
        remark: ""
      },
      expandRow: [],
      addFrom: {},
      editFrom: {},
      deptIds: "",
      isAdd: true,
      seleData: [],
      openText: "全部收起",

      rules: {
        name: [{ required: true, message: "请输入部门名称", trigger: "blur" }]
        // pid: [{ required: true, message: "请选择部门", trigger: "change" }],
      },
      checkedKeys: false,
      isExpansion: true,
      isdeptIds: false
    };
  },
  mounted() {
    this.init();
  },
  computed: {},
  methods: {
    selectRow(val) {
      console.log("val :>> ", val);
    },
    // 解决全选无法选中子节点问题
    selectAll() {
      console.log("object :>> ", "all");
      this.checkedKeys = !this.checkedKeys;
      this.splite(this.tableData, this.checkedKeys);
    },
    splite(data, flag) {
      data.forEach(row => {
        this.$refs.diffeDataTable.toggleRowSelection(row, flag);
        if (row.children) {
          this.splite(row.children, flag);
        }
      });
    },
    handleOpen() {
      if (this.tableData.length) {
        this.isExpansion = !this.isExpansion;
        this.openText = this.openText == "全部展开" ? "全部收起" : "全部展开";
        this.toggleRowExpansion_forAll(
          this.tableData,
          this.openText == "全部展开" ? false : true
        );
      }
    },
    toggleRowExpansion_forAll(data, isExpansion) {
      console.log("data :>> ", data, isExpansion);
      data.forEach(item => {
        this.$refs.diffeDataTable.toggleRowExpansion(item, isExpansion);
        if (item.children) {
          this.toggleRowExpansion_forAll(item.children, isExpansion);
        }
      });
    },
    searchTreeTable() {
      var searchValue = this.searchFrom.name;
      let treeData = _.cloneDeep(this.tableDataClone);
      if (searchValue) {
        let handleTreeData = this.handleTreeData(treeData, searchValue);
        this.setExpandRow(handleTreeData);
        this.expandRow = this.expandRow.join(",").split(",");
        this.tableData = handleTreeData;
        // return handleTreeData;
        console.log("handleTreeData :>> ", handleTreeData);
      } else {
        this.tableData = treeData;
      }
      this.switchText = this.searchFrom.name ? "显示筛选(已筛选)" : "显示筛选";

      // return this.tableData;
    },
    // 选择部门
    handleChange(val) {},
    reSet() {
      this.searchFrom.name = "";
      this.switchText = "显示筛选";
      this.init();
    },
    handleSelectionChange(val) {
      this.deptIds = val.map(item => item.id).join(",");
    },
    onSubmit() {
      this.$refs["formName"].validate(valid => {
        // 等于2 选择部门
        // if (this.form.topDep === 2) {
        // }
        if (valid) {
          this.sumbitLoading = true;
          if (this.isAdd) {
            depCreate({
              name: this.form.name,
              remark: this.form.remark,
              pid:
                this.form.topDep == 1 || this.form.pid.length == 0
                  ? 0
                  : this.form.pid[this.form.pid.length - 1]
            })
              .then(res => {
                this.$msg({
                  type: "success",
                  message: "添加成功!"
                });
                this.init();
                this.clearValidate();
                this.dialogVisible = false;
              })
              .finally(f => {
                this.sumbitLoading = false;
              });
          } else {
            delete this.form.createTime;
            delete this.form.updateTime;
            depEdit({
              ...this.form,
              pid:
                this.form.topDep == 1
                  ? 0
                  : this.form.pid[this.form.pid.length - 1]
            })
              .then(res => {
                this.$msg({
                  type: "success",
                  message: "编辑成功!"
                });
                this.init();
                this.clearValidate();
                this.dialogVisible = false;
              })
              .finally(f => {
                this.sumbitLoading = false;
              });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleEdit(row) {
      this.setDisabled(this.seleData, row.id);
      this.isAdd = false;
      let form = _.cloneDeep(row);
      form.topDep = form.parentId === 0 ? 1 : 2;
      // this.editFrom = row;
      form.pid = form.parentId;

      this.dialogVisible = true;
      this.$nextTick(() => {
        // this.clearValidate();
        this.form = form;
      });
    },
    // 设置自己一下的子级不能选择
    setDisabled(data, id) {
      for (let i = 0; i < data.length; i++) {
        const item = data[i];
        if (item.id == id) {
          console.log("item :>> ", item);
          this.$set(item, "disabled", true);
          if (item.children) {
            this.setDisabledTrue(item.children, true);
          }
        } else {
          this.$set(item, "disabled", false);
          if (item.children) {
            this.setDisabled(item.children, id);
          }
        }
      }
    },
    setDisabledTrue(data, isDis) {
      data.forEach(item => {
        this.$set(item, "disabled", isDis);
        if (item.children) {
          this.setDisabledTrue(item.children, isDis);
        }
      });
    },
    handleDel(id) {
      if (!id) {
        return;
      }
      this.$confirm(
        "删除部门,将会自动解除在此部门下的所有用户与之关系,您可以为这些用户重新设置其它的部门：确认删除此部门吗?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        depDelete(id).then(res => {
          this.$msg({
            type: "success",
            message: "删除成功!"
          });
          this.init();
        });

        // that.getStatusToken();
      });
    },
    handleAdd() {
      this.isAdd = true;
      this.form.name = "";
      this.form.pid = [];
      this.form.topDep = 1;
      this.dialogVisible = true;
      this.setDisabledTrue(this.seleData, false);
      this.$nextTick(() => {
        this.clearValidate();
      });
    },
    clearValidate() {
      this.$refs["formName"].resetFields();
      this.$refs["formName"].clearValidate();
    },
    handleClose() {
      this.clearValidate();
      this.dialogVisible = false;
    },
    init() {
      getDeptList({ name: this.name }).then(res => {
        const { data } = res.data;
        this.tableData = data ? data : [];
        this.$nextTick(() => {
          this.toggleRowExpansion_forAll(this.tableData, true);
        });
        this.tableDataClone = _.cloneDeep(this.tableData);
        // 弹框内部门单独赋值
        this.seleData = _.cloneDeep(this.tableData);
        console.log("res :>> ", this.tableDataClone);
      });
    },
    //  树形表格过滤
    handleTreeData(treeData, searchValue) {
      if (!treeData || treeData.length === 0) {
        return [];
      }
      const array = [];
      for (let i = 0; i < treeData.length; i += 1) {
        let match = false;
        for (let pro in treeData[i]) {
          if (typeof treeData[i][pro] == "string") {
            match |= treeData[i][pro].includes(searchValue);
            if (match) break;
          }
        }
        if (
          this.handleTreeData(treeData[i].children, searchValue).length > 0 ||
          match
        ) {
          array.push({
            ...treeData[i],
            children: this.handleTreeData(treeData[i].children, searchValue)
          });
        }
      }
      return array;
    },
    // 将过滤好的树形数据展开
    setExpandRow(handleTreeData) {
      if (handleTreeData.length) {
        for (let i of handleTreeData) {
          this.expandRow.push(i.id);
          if (i.children.length) {
            this.setExpandRow(i.children);
          }
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.all_open {
  display: flex;
  width: 100%;
  justify-content: space-between;
  margin-top: 10px;
  .open_close {
    display: flex;
    align-items: center;
    cursor: pointer;
    .open_text {
      font-size: 14px;
      margin-left: 4px;
    }
  }
}
.department_box {
  width: 100%;
  display: flex;
  justify-content: space-between;
  .department_table {
    width: 100%;
    background-color: #fff;
    /deep/ .el-table {
      margin-bottom: 0 !important;
      .cell {
        white-space: nowrap !important;
      }
    }
  }
  .department_tree_box {
    width: 16%;
    padding: 20px;
    background-color: #fff;
  }
  .department_tree {
    width: 100%;
    margin-top: 10px;
  }
}
</style>
